<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 150px;
            height: 150px;
            background-color: #6ff;
            position: absolute;
            left: 150px;
            top: 150px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    // 面向过程
    // 1. 获取元素
    // 2. 鼠标按下  记录按下的位置
    // 3. 鼠标移动  盒子跟随鼠标移动
    // 4. 鼠标抬起  盒子不在移动  

    var box = document.getElementsByClassName("box")[0];

    box.onmousedown = function (e) {
        var e = e || window.event;
        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX, posY);

        document.onmousemove = function (e) {
            var e = e || window.event;
            var x = e.pageX - posX;
            var y = e.pageY - posY;

            box.style.left = x + 'px';
            box.style.top = y + 'px';
        }

        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }

    }





</script>

</html>